package com.klarna.raas.ws.webservices.rest;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.blog.samples.domain.Fund;
import com.klarna.raas.ws.domain.PersonInfo;
import com.klarna.raas.ws.services.LookupService;

/**
 * PersonLookupController class will expose a series of RESTful endpoints
 */
@Controller
public class PersonLookupController {

	@Autowired
	private LookupService lookupService;

	@Autowired
	private View jsonView;

	private static final String DATA_FIELD = "data";
	private static final String ERROR_FIELD = "error";

	private static final Logger logger = Logger.getLogger(PersonLookupController.class);

	/**
	 * Gets a person by person ID.
	 *
	 * @param id
	 *            the person id
	 * @return the person info
	 */
	@RequestMapping(value = "/rest/credbureau/{id}", method = RequestMethod.GET)
	public ModelAndView getPersonInfo(@PathVariable("id") String id) {
		PersonInfo person = null;

		// validate person ID parameter
		if (isEmpty(id)) {
			String sMessage = "Error invoking getPersonInfoById - Invalid person ID! id=" + id;
			return createErrorResponse(sMessage);
		}

		try {
			person = lookupService.getPersonInfoById(id);
		} catch (Exception e) {
			String sMessage = "Error invoking getPersonInfoById. [%1$s]";
			return createErrorResponse(String.format(sMessage, e.toString()));
		}

		logger.debug("Returing PersonInfo: " + person.toString());
		return new ModelAndView(jsonView, DATA_FIELD, person);
	}


	/*
	 *
  birth_date,
  first_name,
  last_name,
  street,
  zip,
	 */
	/**
	 * Gets a person by person ID.
	 *
	 * @param id
	 *            the person id
	 * @return the person info
	 */
	@RequestMapping(value = "/rest/credbureau", params={"birth_date", "first_name","last_name","street","zip"},  method = RequestMethod.GET)
	public ModelAndView getPersonInfoByMyltipleParams(
			@RequestParam(value = "birth_date") String birthDate,			
			@RequestParam(value = "first_name") String firstName,			
			@RequestParam(value = "last_name") String lastName,			
			@RequestParam(value = "street") String street,			
			@RequestParam(value = "zip") String zip) {
				PersonInfo person = null;

				logger.info("getPersonInfoByMyltipleParams START");

				String paramsMessage = "Params recieved[" +
						"birthDate=" + birthDate
						+ ",firstName=" + firstName
						+ ",lastName=" + lastName
						+ ",street=" + street
						+ ",zip=" + zip
						+ "]";
				
				logger.info(paramsMessage);
				
				// validate request parameters parameter
				if (isEmpty(birthDate) || isEmpty(firstName) || isEmpty(lastName) || isEmpty(street) || isEmpty(zip)) {
					String sMessage = "Error invoking getPersonInfoByMyltipleParams - Invalid params recieved! [" +
							" birthDate=" + birthDate
							+ ",firstName=" + firstName
							+ ",lastName=" + lastName
							+ ",street=" + street
							+ ",zip=" + zip
							+ "]"
							;
					logger.error(sMessage);
					
					return createErrorResponse(sMessage);
				}

				try {
					person = lookupService.getPersonInfoByMultipleParams(birthDate, firstName, lastName, street, zip);
				} catch (Exception e) {
					String sMessage = "Error invoking getPersonInfoById. [%1$s]";
					return createErrorResponse(String.format(sMessage, e.toString()));
				}

				logger.debug("Returing PersonInfo: " + person);
				logger.info("getPersonInfoByMyltipleParams END");

				return new ModelAndView(jsonView, DATA_FIELD, person);
			}



			public static boolean isEmpty(String s_p) {
				return (null == s_p) || s_p.trim().length() == 0;
			}

			/**
			 * Create an error REST response.
			 *
			 * @param sMessage
			 *            the s message
			 * @return the model and view
			 */
			private ModelAndView createErrorResponse(String sMessage) {
				return new ModelAndView(jsonView, ERROR_FIELD, sMessage);
			}

			/**
			 * Injector methods.
			 *
			 * @param lookupService
			 *            the new LookupService
			 */
			public void setLookupService(LookupService lookupService) {
				this.lookupService = lookupService;
			}

			/**
			 * Injector methods.
			 *
			 * @param view
			 *            the new json view
			 */
			public void setJsonView(View view) {
				jsonView = view;
			}

}
